package com.treeliked.netdiskdemo.util;

import com.treeliked.netdiskdemo.model.Response;
import com.treeliked.netdiskdemo.model.ResultCode;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 文件工具类
 *
 * @author lqs2
 * @date 2018/11/30, Fri
 */
public class FileUtils {

    /**
     * 当前类加载器
     */
    private static ClassLoader loader;


    static {
        loader = FileUtils.class.getClassLoader();
    }


    /**
     * 递归删除文件夹及其所有内容
     *
     * @param dir 文件夹
     */
    public static boolean deleteFolder(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            assert children != null;
            for (String aChildren : children) {
                boolean success = deleteFolder(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录为空，可以删除
        return dir.delete();
    }


    /**
     * 新建文件到指定的路径
     *
     * @param bytes 文件数组
     * @param path  文件路径
     * @return 是否保存成功
     */
    public static boolean saveFile(byte[] bytes, String path, Response response) throws IOException {
        String dir = path.substring(0, path.lastIndexOf("/"));
        String name = path.substring(path.lastIndexOf("/") + 1);
        File temp = new File(dir);
        if (!temp.exists()) {
            temp.mkdirs();
        }
        File file = new File(dir + File.separator + name);
        if (file.exists()) {
            response.setCode(ResultCode.FAIL);
            response.setMessage("文件【" + name + "】已经存在");
            return false;
        }
        file.createNewFile();

        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        out.write(bytes);
        out.flush();
        out.close();
        return true;
    }


    /**
     * 获取文件后缀
     *
     * @param name 文件路径
     */
    public static String getFileSuffixThroughName(String name) {
        return name.substring(name.lastIndexOf(".") + 1);
    }


    /**
     * 设置下载响应头，其中encoded_text是经过RFC 3986的“百分号URL编码”规则处理过的文件名
     *
     * @param response http响应
     * @param filename 下载的文件名
     */
    public static void setFileDownloadHeader(HttpServletResponse response, String filename) {
        String headerValue = "attachment;";
        headerValue += " filename=\"" + encodeURIComponent(filename) + "\";";
        headerValue += " filename*=utf-8''" + encodeURIComponent(filename);
        response.setHeader("Content-Disposition", headerValue);
        response.setContentType("application/force-download");
    }

    /**
     * 符合 RFC 3986 标准的“百分号URL编码”
     * 在这个方法里，空格会被编码成%20，而不是+
     * 和浏览器的encodeURIComponent行为一致
     *
     * @param value 需要编码的值
     * @return 编码后的值
     */
    private static String encodeURIComponent(String value) {
        try {
            return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
}
